import pymysql


class MysqlQueue():

    def __init__(self):  # 初始mysql连接
        try:
            self.db = pymysql.connect(  # 连接数据库
                host="127.0.0.1",
                user="root", password="",
                database="spider",
                charset="utf8")
            print('数据库成功连接')
            self.cur = self.db.cursor()  # 创建游标
        except pymysql.Error as e:  #连接失败或者 创建表失败
            print(str(e))

    def create_table(self):
        try:
            self.cur.execute("drop table if exists img_url")
            sql ="CREATE TABLE spider ( id int(10) NOT NULL AUTO_INCREMENT, title varchar(10) NULL, imgurl varchar(255) NULL,  PRIMARY KEY (id) )"
            self.cur.execute(sql)
            print('成功创建表')
        except pymysql.Error as e:
            print(str(e))

    def insert(self,title,imgurl):
        try:
            sql="insert into spider(id,title,imgurl) values(null,'{}','{}')".format(title,imgurl)
            self.cur.execute(sql)
            self.db.commit()
            print(imgurl, '插入表成功')
        except errors.Error as e:  
            print(imgurl, '插入数据失败')
            self.db.rollback()
    
    def close(self):
        self.db.close()



